#include"ShareMemory.h"

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>

#include<sys/types.h>
#include<sys/shm.h>

struct SharedMemory
{
    key_t key;
    int shmid;
    void *data;
    size_t size;
};

ShMemory *InitSharedMemory(const char *pathname, int pro_id, size_t size)
{
    ShMemory *m=(ShMemory *)malloc(sizeof(ShMemory));
    if(m==NULL)
    {
        printf("InitSharedMemory malloc error!\n");
        return NULL;
    }

    m->key=ftok(pathname,pro_id);
    if(m->key<0)
    {
        perror("fork:");
        return NULL;
    }

    m->size=size;
    m->shmid=shmget(m->key,size,IPC_CREAT|0777);
    if(m->shmid<0)
    {
        perror("ShmID:");
        free(m);
        return NULL;
    }
    return m;
}

void ClearSharedMemory(ShMemory *m)
{
    if(shmctl(m->shmid,IPC_RMID,NULL)==-1)
    {
        perror("shmctl:");
    }
    free(m);
}

void ReadFormSharedMenory(ShMemory *m, void *ptr, size_t size)
{
    if(size>m->size)
    {
        printf("the size is bigger than SharedMemory!\n");
        return;
    }

    void *text=shmat(m->shmid,NULL,0);
    if(text==(void *)-1)
    {
        perror("shmat:");
        return;
    }
    memcpy(ptr,text,size);

    if(shmdt(text)==-1)
    {
        perror("shmdt:");
        return;
    }
}

void WriteToSharedMenory(ShMemory *m, void *ptr, size_t size)
{
    if(size>m->size)
    {
        printf("the size is bigger than SharedMemory!\n");
        return;
    }

    void *text=shmat(m->shmid,NULL,0);
    if(text==(void *)-1)
    {
        perror("shmat:");
        return;
    }
    memcpy(text,ptr,size);

    if(shmdt(text)==-1)
    {
        perror("shmdt:");
        return;
    } 
    free(m);
}
